# 450 中等：删除二叉搜索树中的节点

# Definition for a binary tree node.
# class HOT.TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def deleteNode(self, root: Optional[HOT.TreeNode], key: int) -> Optional[HOT.TreeNode]:
        if root is None:
            return None
        if root.val < key:
            root.right = self.deleteNode(root.right, key)
        elif root.val > key:
            root.left = self.deleteNode(root.left, key)
        elif root.left is None or root.right is None:
            root = root.left if root.right is None else root.right
        else:
            cur = root.right
            while cur.left:
                cur = cur.left
            cur.right = self.deleteNode(root.right, cur.val)
            cur.left = root.left
            return cur

        return root
